import 'package:flutter/material.dart';
import 'package:juju/conf/IMConf.dart';
import 'package:juju/control/JmessageCtl.dart';
import 'package:juju/default/Kits.dart';
import 'package:juju/fake/fake_message_tool.dart';
import 'package:juju/model/ChatDataModel.dart';
import 'package:juju/model/ConversationDataModel.dart';
import 'package:juju/model/EventQueueModel.dart';

class MessagePage extends StatefulWidget {
  const MessagePage({Key? key}) : super(key: key);

  @override
  State<MessagePage> createState() => _MessagePageState();
}

class _MessagePageState extends State<MessagePage> {
  ChatDataModel chatDataModel = ChatDataModel(); //数据传输对象

  ConversationInfo? selectConversationInfo; //选中的会话

  ///============================================
  /// 侧边抽屉视图
  ///============================================
  final ListView _listViewDrawer = ListView(
    padding: EdgeInsets.zero,
    children: const <Widget>[
      DrawerHeader(
        child: Text(
          'Drawer Header',
          style: TextStyle(
            fontSize: 24,
          ),
        ),
      ),
      ListTile(
        leading: Icon(Icons.message),
        title: Text('Messages'),
      ),
      ListTile(
        leading: Icon(Icons.account_circle),
        title: Text('Profile'),
      ),
      ListTile(
        leading: Icon(Icons.settings),
        title: Text('Settings'),
      ),
    ],
  );

  @override
  void initState() {
    super.initState();
    print(
        "======================== MessagePage : Init =======================");
    _getConversationList();
  }

  @override
  Widget build(BuildContext context) {
    print(
        "======================== MessagePage : Build =======================");
    // _getConversationList();
    return Scaffold(
      appBar: AppBar(
        title: const Text("聚聚"),
        actions: <Widget>[
          IconButton(
            icon: const Icon(Icons.fiber_new),
            onPressed: _gotoNewFriendsPage,
          )
        ],
      ),
      body: Container(
        color: Colors.grey[50],
        child: ListView.builder(
          itemBuilder: _itemBuilder,
          itemCount:
              ConversationDataModel.getInstance().conversationList.length,
        ),
      ),
      drawer: Drawer(
        child: _listViewDrawer,
      ),
    );
  }

  ///========================================
  /// 会话列表构建器
  ///========================================
  Widget _itemBuilder(BuildContext buildContext, int position) {
    // print(position);
    UserInfo target = ConversationDataModel.getInstance()
        .conversationList
        .elementAt(position)
        .target;
    TextMessage? last = ConversationDataModel.getInstance()
        .conversationList
        .elementAt(position)
        .latestMessage;
    // String avatarThumbPath = _getTargetUserAvatar(target.username) as String;
    print("======================= avatarPath =====================");
    print("|\n|\n----- ${target.avatarThumbPath}\n");
    // print("|\n|\n----- ${avatarThumbPath}\n");

    return Container(
      padding: const EdgeInsets.only(
        top: 5.0,
        bottom: 5.0,
      ),
      decoration: BoxDecoration(
        border: Border(bottom: BorderSide(color: Colors.grey[300]!)),
      ),
      child: ListTile(
        leading: Container(
          clipBehavior: Clip.hardEdge,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(15.0),
          ),
          child: avatar(target.avatarThumbPath),
        ),
        title: Text(target.username),
        subtitle: Text(last == null ? "" : last.text),
        onTap: () => _gotoChatPage(dataIndex: position),
      ),
    );
  }

  ///========================================
  /// 跳转会话页面
  ///========================================
  void _gotoChatPage({required int dataIndex}) {
    selectConversationInfo =
        ConversationDataModel.getInstance().conversationList[dataIndex];
    UserInfo u = selectConversationInfo!.target;
    _getHistorMessage();
    chatDataModel.target = Single.fromJson({
      'username': u.username,
    });
    chatDataModel.conversationInfo = selectConversationInfo;
    Navigator.pushNamed(context, "ChatPage", arguments: chatDataModel);
  }

  ///========================================
  /// 历史消息
  ///========================================
  void _getHistorMessage() async {
    print(
        "===================== START : getHistorMessage ====================\n");

    selectConversationInfo!
        .getHistoryMessages(from: 0, limit: 20)
        .then((msgList) {
      chatDataModel.msgList = msgList;
      print("|\n|\n----- ${msgList.toString()}");
      print(
          "===================== END : getHistorMessage ====================\n");
    });
  }

  ///========================================
  /// 退出登录
  ///========================================
  void logoutAction() async {
    print("======================= LogOut =====================");
    IMConf.getInstance().getJmessage().logout();
    print("======================= LogOut =====================");
    UserInfo? jmUserInfo = await IMConf.getInstance().getJmessage().getMyInfo();
    if (jmUserInfo == null) {
      print(" ===== 您已退出 ===== \n【获取登录用户信息】null");
      EventQueueModel.getInstance().fieldClear();
      Navigator.of(context).pushReplacementNamed("Welcome");
    } else {
      print(" ===== 您已经登录 ===== \n【获取登录用户信息】${jmUserInfo.toJson()}");
    }
  }

  // Future<String> _getTargetUserAvatar(String target) async {
  //   Map resJson = await IMConf.getInstance()
  //       .getJmessage()
  //       .downloadThumbUserAvatar(username: 'theUserName');
  //   return resJson["filePath"];
  // }

  void _gotoNewFriendsPage() {
    Navigator.of(context).pushNamed("NewFriends");
  }

  void _getConversationList() async {
    await getConversationListCtl();
    setState(() {});
  }
}
